home *** CD-ROM | disk | FTP | other *** search
- Path: news.umbc.edu!not-for-mail
- From: schlein@umbc.edu (Jonas J. Schlein)
- Newsgroups: comp.lang.c
- Subject: Re: Calling a Function Twice from a printf statement.
- Date: 7 Mar 1996 17:49:04 -0500
- Organization: University of Maryland Baltimore County
- Message-ID: <4hnp50$ua@umbc9.umbc.edu>
- References: <4he6q9$6r6@newsbf02.news.aol.com>
- NNTP-Posting-Host: umbc9.umbc.edu
- NNTP-Posting-User: schlein
-
- Razine <razine@aol.com> wrote:
- |> I am trying to call a function twice from my program on the same printf
- |> line and have run into a small problem. i was wondering if someone can
- |> explain how to fix it.
- |>
- |> void main(void) {
-
- Well as soon as you give an incorrect definition for main() that immediately
- introduces possible undefined behavior to your program. Make it
- 'int main (void)'.
-
- |> printf("First Number is %d , the Second s %d \n",num(0),num(1));
-
- Not giving a prototype for a variadic function like printf() can lead
- to unexpected results as well. Please #include <stdio.h>.
-
- |> }
- |>
- |> int num(int index) {
- |> int return_number;
- |>
- |> switch(index) {
- |> case 0 : return_number=0;
- Add: break;
- |> case 1 : return_number=1;
- Add: break;
- |> }
- |> return(return_number);
-
- Note that this is probably garbage if 'index' is other than 0 or 1.
- |> }
- |>
- |> Now with this function, the printf line will display 0 for the first one
- |> and garbage for the second one.. I then thought if I made the variable
- |> return_number a static variable it would have fixed it but then when i
- |> made the change the printf line would give me zero for both of them. Any
- |> ideas?
-
- Static is certainly the *WRONG* choice since that will make the function
- unable to be called twice in 1 printf() statement. This is due to the
- static variable being overridden on subsequent calls to the function.
- The solution is to use switch() properly and define functions properly.
- --
- "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
-
- Jonas J. Schlein (schlein@gl.umbc.edu)
-